package com.junjie.checkin.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.junjie.checkin.entity.TPointRecord;
import com.junjie.checkin.mapper.PointRecordMapper;
import com.junjie.checkin.request.pointRecord.PointRecordAdminPageRequest;
import com.junjie.checkin.request.pointRecord.PointRecordPageRequest;
import com.junjie.checkin.response.PageResult;
import com.junjie.checkin.response.admin.DisciplinaryRecordsResponse;
import com.junjie.checkin.response.front.ActivityFrontResponse;
import com.junjie.checkin.response.pointRecord.PointRecordResponse;
import com.junjie.checkin.security.service.JwtService;
import com.junjie.checkin.security.service.impl.JwtServiceImpl;
import com.junjie.checkin.utils.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 洪浚杰
 * @description
 * @date 2025/6/18 14:18
 */
@Service
public class PointRecordService {
    @Autowired
    private JwtServiceImpl jwtService;
    @Autowired
    private PointRecordMapper pointRecordMapper;

    /**
     * 获取当前用户的积分明细列表
     * @param pageRequest 积分明细列表参数
     * @param token 用户token
     */
    public PageResult<PointRecordResponse> getPointRecord(PointRecordPageRequest pageRequest, String token){
        pageRequest.initDefault();
        Integer userId = jwtService.analyzeToken(token).getUser().getId();
        PageHelper.startPage(pageRequest.getPage(),pageRequest.getPageSize());
        Page<TPointRecord> pointRecords = pointRecordMapper.pageQueryPointRecordList(userId, pageRequest.getType(), pageRequest.getReason(), pageRequest.getIncrease());
        // 格式化结果
        List<PointRecordResponse> responses = pointRecords.getResult().stream().map(pointRecord -> {
            PointRecordResponse response = new PointRecordResponse();
            System.out.println(pointRecord.getId());
            BeanUtils.copyProperties(pointRecord, response);
            response.setCreateTime(DateTimeFormat.dateToString(pointRecord.getCreateTime()));
            return response;
        }).toList();
        return new  PageResult<PointRecordResponse>(pointRecords.getTotal(),responses);
    }


    /**
     * 获取用户积分记录
     * @param request
     * @return
     */
    public PageResult<DisciplinaryRecordsResponse> getPointRecordPage(PointRecordAdminPageRequest request) {
        PageHelper.startPage(request.getPage(), request.getPageSize());
        Page<DisciplinaryRecordsResponse> page = pointRecordMapper.getPointRecordPage(request);
        return new PageResult<>(page.getTotal(), page.getResult());
    }
}
